﻿using Jiguang.JPush;
using Jiguang.JPush.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace PmSoft.Jiguang
{
    /// <summary>
    /// 极光推送
    /// </summary>
    [UseDI(ServiceLifetime.Scoped)]
    public class JiguangRepository
    {
        private readonly IConfiguration configuration;
        private readonly JPushClient client;
        private readonly ILogger logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="logger"></param>
        public JiguangRepository(IConfiguration configuration, ILogger<JiguangRepository> logger)
        {
            this.configuration = configuration;
            this.logger = logger;
            string? appKey = configuration.GetValue<string>("ThreePartyOptions:Jiguang:AppKey");
            string? masterSecret = configuration.GetValue<string>("ThreePartyOptions:Jiguang:MasterSecret");
            client = new JPushClient(appKey, masterSecret);

        }

        /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="payload"></param>
        public async Task SendPush(PushPayload payload)
        {
            try
            {
                var result = await client.SendPushAsync(payload);
                logger.LogWarning($"推送完成：" + JsonSerializer.Serialize(result));
            }
            catch (Exception e)
            {
                logger.LogError($"激光消息推送失败：{e.Message}");
            }
        }
    }
}
